package com.ptu.spzx.manager.service.impl;

import com.ptu.spzx.common.exception.ptuException;
import com.ptu.spzx.manager.mapper.SysDeptMapper;
import com.ptu.spzx.manager.service.DeptService;
import com.ptu.spzx.manager.utils.DeptHelper;
import com.ptu.spzx.model.entity.system.SysDept;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import com.ptu.spzx.model.vo.system.SysDeptVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Override
    public void removeById(Long id) {
        //根据当前的菜单id来查询是否包含子菜单
        int count=sysDeptMapper.selectCountById(id);
        //判断，count大于0，包含子菜单
        if(count>0){
            throw  new ptuException(ResultCodeEnum.NODE_ERROR);
        }
        //count等于0，直接删除
        sysDeptMapper.delete(id);
    }

    @Override
    public void update(SysDept sysDept) {
        sysDeptMapper.update(sysDept);
    }

    @Override
    public void save(SysDept sysDept) {
        sysDeptMapper.save(sysDept);
    }

    @Override
    public List<SysDeptVo> findNodes() {
        List<SysDept> sysDepts = sysDeptMapper.selectAll();
        //根据userId查询出可以操作的菜单
        //封装要求的数据格式，返回
        List<SysDept> sysDeptList = DeptHelper.buildTree(sysDepts);
        List<SysDeptVo> sysDeptVos = this.buildDepts(sysDeptList);

        return sysDeptVos;
    }

    @Override
    public List<SysDept> findDeptAll() {
       return sysDeptMapper.selectAll();
    }

    private List<SysDeptVo> buildDepts(List<SysDept> menus) {

        List<SysDeptVo> sysDeptVoList = new LinkedList<SysDeptVo>();
        for (SysDept sysDept : menus) {
            SysDeptVo sysDeptVo = new SysDeptVo();
            sysDeptVo.setDeptName(sysDept.getDeptName());
            List<SysDept> children = sysDept.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                sysDeptVo.setChildren(buildDepts(children));
            }
            sysDeptVoList.add(sysDeptVo);
        }
        return  sysDeptVoList;
    }


}
